package com.ksc.storekeeper.client.view.impl;

import com.github.gwtbootstrap.client.ui.Button;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.ViewImpl;
import com.ksc.storekeeper.client.view.ChangeRoleView;
import com.ksc.storekeeper.client.view.components.FormItemListBox;
import com.ksc.storekeeper.client.view.components.FormItemTextBox;
import com.ksc.storekeeper.shared.auth.Authorities;

public class ChangeRoleViewImpl extends ViewImpl implements ChangeRoleView {

	private final Widget widget;
	private final ChangeRoleViewUiBinder uiBinder = GWT.create(ChangeRoleViewUiBinder.class);
	private ChangeRoleUiHandler uiHandler;

	@UiField
	HTML infoMsg;

	@UiField
	Button changeRole;

	@UiField
	FormItemTextBox username;

	@UiField
	FormItemListBox roles;

	interface ChangeRoleViewUiBinder extends UiBinder<Widget, ChangeRoleViewImpl> {

	}

	public ChangeRoleViewImpl() {
		widget = uiBinder.createAndBindUi(this);
		roles.addItem(Authorities.ROLE_ADMIN, "1");
		roles.addItem(Authorities.ROLE_STOREKEEPER, "2");
	}

	@Override
	public Widget asWidget() {
		return this.widget;
	}

	private boolean validate() {
		boolean valid = username.validate() & roles.validate();
		return valid;
	}

	@Override
	public void setUiHandlers(ChangeRoleUiHandler uiHandlers) {
		this.uiHandler = uiHandlers;
	}

	@UiHandler("changeRole")
	public void onChangeRoleClicked(final ClickEvent event) {
		if (validate()) {
			String userName = username.getText();
			String role = roles.getItemText(roles.getSelectedIndex());
			uiHandler.changeRole(userName, role);
		}
	}

}
